﻿using System;
using System.Diagnostics;
using System.Security;

namespace Borg.Logging
{
    internal sealed class EventViewLogger : TextLoggerBase
    {
        private int _id;
        private string _company;
        private string _application;

        public override void Init(Runtime runtime)
        {
            base.Init(runtime);

            _company = runtime.Application.Company;
            _application = runtime.Application.Name;

            if (!LogSourceExists(_application))
                EventLog.CreateEventSource(_application, _company);
            
            Log(new LogArgs(LogType.Info, this, "{0}", new object[] { Runtime.VersionInfo }));
        }

        private static bool LogSourceExists(string source)
        {
            try { return EventLog.SourceExists(source); }
            catch (SecurityException) { return false; }
        }

        public override void Log(LogArgs args)
        {
            EventLog.WriteEntry(_application, args.Message,
                LogTypeToEventLogEntryType(args.Type), _id++);
        }

        private static EventLogEntryType LogTypeToEventLogEntryType(LogType logType)
        {
            switch (logType)
            {
                case LogType.Info:
                    return EventLogEntryType.Information;
                
                case LogType.Warning:
                    return EventLogEntryType.Warning;
                
                case LogType.Error:
                    return EventLogEntryType.Error;
                
                default:
                    throw new ArgumentException("unknown logType: " + logType);
            }
        }
    }
}
